package com.ldzg.blockwatcher.config.eth;

import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.http.HttpService;
import org.web3j.protocol.websocket.WebSocketService;

import java.net.ConnectException;


/**
 * @author dengyangjie
 */
@Configuration
@RequiredArgsConstructor
public class Web3jConfig {

    public static final String INCLINED = "/";
    final EthProperties ethProperties;


    @Bean
    public Web3j web3j() throws ConnectException {
        String ethUrl = ethProperties.getEthUrl();
        if (!StringUtils.endsWith(ethUrl, INCLINED)) {
            ethUrl = ethUrl + INCLINED;
        }
        String listenUrl = ethUrl.concat(ethProperties.getApiKey());

        WebSocketService webSocketService = new WebSocketService(listenUrl, Boolean.TRUE);
        webSocketService.connect();

        return Web3j.build(webSocketService);
    }
}
